package com.ruoyi.mail.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;

import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

import com.ruoyi.mail.model.MailMessageInfo;
import com.ruoyi.mail.service.MailManagementService;
import com.sun.mail.imap.IMAPFolder;

@Service
public class MailManagementServiceImpl implements MailManagementService {

    protected final JavaMailSenderImpl javaMailSender;

    public MailManagementServiceImpl(JavaMailSenderImpl javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    @Override
    public void ChangeMailSetting(String userName, String passWord) {
        javaMailSender.setUsername(userName);
        javaMailSender.setPassword(passWord);
    }

    @Override
    public List<String> getFolderNames() throws MessagingException {
        List<String> strNames= new ArrayList<>();
        Session session = javaMailSender.getSession();
        Store store = session.getStore("imaps");
        store.connect(javaMailSender.getHost(), javaMailSender.getUsername(), javaMailSender.getPassword());
        IMAPFolder defaultFolder = (IMAPFolder) store.getDefaultFolder();
        if (null != defaultFolder.listSubscribed() && defaultFolder.listSubscribed().length > 0) {
            for (Folder folder : defaultFolder.listSubscribed()) {
                strNames.add(folder.getName());
            }
        }
        return strNames;
    }

    @Override
    public List<MailMessageInfo> getMailMessageInfos(String folderName) throws MessagingException {
        Session session = javaMailSender.getSession();
        Store store = session.getStore("imaps");
        store.connect(javaMailSender.getHost(), javaMailSender.getUsername(), javaMailSender.getPassword());
        IMAPFolder folder = (IMAPFolder) store.getFolder(folderName);
        folder.open(Folder.READ_WRITE);
        Message[] messages = folder.getMessages();
        List<MailMessageInfo> mailMessageInfos= new ArrayList<>();
        for (Message message :  messages) {
            MailMessageInfo mailMessageInfo= new MailMessageInfo();

            mailMessageInfo.setMailSubject(message.getSubject());

            mailMessageInfos.add(mailMessageInfo);

        }

        return mailMessageInfos;
    }

}
